package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动扫描与当前类Test3在同一个包中那些被@AutoRunClass标注的类
 */
public class Test3 {
    public static void main(String[] args) {
        try {
            File file = new File(Test3.class.getResource(".").toURI());
            File[] files = file.listFiles(f->f.getName().endsWith(".class"));
            for(File f : files){
                String fileName = f.getName();
                String[] data = fileName.split("\\.");
                String className = data[0];
                Class c = Class.forName(Test3.class.getPackage().getName() + "." + className);
                if(c.isAnnotationPresent(AutoRunClass.class)){
                    Object obj = c.newInstance();
                    System.out.println(obj);
                    Method[] methods = c.getMethods();
                    for (Method m : methods){
                        if (m.isAnnotationPresent(AutoRunMethod.class)){
                            AutoRunMethod arm = m.getAnnotation(AutoRunMethod.class);//获取注解
                            int value = arm.value();
                            String name = arm.name();
                            System.out.println(name);
                            for (int i = 0; i < value; i++) {
                                m.invoke(obj);
                            }
                        }
                    }

                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
